package com.are.inventario;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.RadioButton;

public class BuscarClienteActivity extends Activity {
	
private ProgressDialog progressDialog;
private Cliente cliente; 
private EditText criterio;
private RadioButton r1, r2,r3,r4;
private String url = "";
	
	private final Handler progressHandler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg.obj != null) {
				cliente = (Cliente) msg.obj;
				ShowMensaje(cliente);
			}
			progressDialog.dismiss();
		}
	};
	

    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
    	
    	switch (item.getItemId()) {
    	case R.id.cmd_buscar:
    		try {
				LoadData();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				crearDialogoAlerta(e.getMessage()).show() ;
			}
    		break;
    	case R.id.cmd_salir:
    		finish();
    		break;
    	}
    	
    	
		return true;
	}

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buscar_cliente);
        criterio = (EditText)findViewById(R.id.txtCriterio);
        r1 = (RadioButton)findViewById(R.id.opt_nic);
        r2 = (RadioButton)findViewById(R.id.opt_nis);
        r3 = (RadioButton)findViewById(R.id.opt_nif);
        r4 = (RadioButton)findViewById(R.id.opt_medidor);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_buscar_cliente, menu);
        return true;
    }
    
    private void LoadData() throws UnsupportedEncodingException {
		progressDialog = ProgressDialog.show(BuscarClienteActivity.this, "",
				"Por favor espere mientras se envian los datos...", true);
		String strCriterio = criterio.getText().toString();
		String tipo = "1";
		if (r1.isChecked()) {
			tipo = "1";
		}else if (r2.isChecked()) {
			tipo = "2";
		}else if (r3.isChecked()) {
			tipo = "3";
		}else if (r4.isChecked()) {
			tipo = "4";
		}
		
		this.url = "http://siscos.fcr.com.co:8080/AreApp/XmlCliente?criterio=" + URLEncoder.encode(strCriterio, "ISO-8859-1") + "&tipo=" + tipo;
		
		new Thread(new Runnable() {
			public void run() {
				XmlParseCliente parse = new XmlParseCliente(url);
				Message msg = progressHandler.obtainMessage();
				msg.obj = parse.parse();
				progressHandler.sendMessage(msg);
			}
		}).start();
	}

	private Dialog crearDialogoAlerta(String mensaje) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Informacion");
		builder.setMessage(mensaje);
		builder.setCancelable(false);
		builder.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});		
		return builder.create();
	}
	
	private void ShowMensaje(Cliente data) {
		if (!data.getNic().equals("")) {
			//AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta("Transformador encontrado " + data.getCodigo());
			//alert.show();
			
			Intent intent = new Intent(this, ClienteActivity.class);
			intent.putExtra("nic", data.getNic());
			intent.putExtra("nis",data.getNis());
			intent.putExtra("nif",data.getNif());
			intent.putExtra("direccion",data.getDireccion());
			intent.putExtra("medidor",data.getMedidor());
			intent.putExtra("marca",data.getMarca());
			startActivity(intent);
			
		} else { // error al confirmar la orden
			AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta("Cliente no encontrado");
			alert.show();
		}
}
}
